package chapter07;

import java.sql.*;
import java.util.Scanner;

public class Test02_prepareStatement {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //链接数据库
            String url = "jdbc:mysql://localhost:3306/" +
                    "studentmanagement?serverTimezone=GMT%2B8&useSSL=false";
            con = DriverManager.getConnection(url,"root","");
            //执行sql语句
            String sql = "select * from student where sname=?";
            pstm = con.prepareStatement(sql);
            //读入条件
            Scanner scanner = new Scanner(System.in);
            String s = scanner.nextLine();
            //处理占位符
            pstm.setString(1,s);
            rs = pstm.executeQuery();
            //处理结果集
            while(rs.next()){
                int id = rs.getInt("id");
                String sno = rs.getString("sno");
                String sname = rs.getString("sname");
                String sgrade = rs.getString("sgrade");
                System.out.println(id+":"+sno+":"+sname+":"+sgrade);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                rs = null;
            }
            if(pstm!=null){
                try {
                    pstm.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                pstm = null;
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                con = null;
            }
        }
    }
}
